<template>
  <layout-content header="Secrets">
    <div style="float: left">
      <el-button
        v-has-permissions="{
          scope: 'namespace',
          apiGroup: '',
          resource: 'secrets',
          verb: 'create'
        }"
        type="primary"
        size="small"
        @click="onShouldYamlCreate"
      >
        YAML
      </el-button>
      <el-button
        v-has-permissions="{
          scope: 'namespace',
          apiGroup: '',
          resource: 'secrets',
          verb: 'create'
        }"
        type="primary"
        size="small"
        @click="onShouldCreate"
      >
        {{ $t("commons.button.create") }}
      </el-button>
      <el-button
        v-has-permissions="{
          scope: 'namespace',
          apiGroup: '',
          resource: 'secrets',
          verb: 'delete'
        }"
        type="primary"
        size="small"
        :disabled="selections.length === 0"
        @click="onShouldDelete()"
      >
        {{ $t("commons.button.delete") }}
      </el-button>
    </div>
    <complex-table
      v-model:selects="selections"
      v-loading="uiState.loading"
      :data="secretList"
      :pagination-config="query.paginationConfig"
      :search-config="query.searchConfig"
      @search="reloadSecretList"
    >
      <el-table-column type="selection" fix />
      <el-table-column
        :label="$t('commons.table.name')"
        prop="metadata.name"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span class="span-link" @click="onSHouldViewDetails(row)">
            {{ row.metadata.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('business.configuration.type')"
        prop="type"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('business.namespace.namespace')"
        prop="metadata.namespace"
        min-width="50px"
      />
      <el-table-column
        :label="$t('commons.table.created_time')"
        prop="metadata.creationTimestamp"
        fix
        min-width="50px"
      >
        <template #default="{ row }">
          {{ row.metadata.creationTimestamp }}
        </template>
      </el-table-column>
      <ko-table-operations
        :buttons="uiState.buttons"
        :label="$t('commons.table.action')"
      />
    </complex-table>
  </layout-content>
</template>

<script setup lang="ts">
import ComplexTable from "@/views/domain/kubeHud/views/components/complex-table/index.vue";
import LayoutContent from "@/views/domain/kubeHud/views/components/layout/LayoutContent.vue";
import KoTableOperations from "@/views/domain/kubeHud/views/components/ko-table-operations/index.vue";
import { useI18n } from "vue-i18n";
import { onMounted, reactive, ref } from "vue";
import { Secret, useK8SApi } from "@/views/domain/kubeHud/api/k8s";
import { useVerifyRouter } from "@/router/use";
import { KRouteSecret } from "@/views/domain/kubeHud/router";
import { ElMessageBox } from "element-plus";
import { checkPermissions } from "@/views/domain/kubeHud/utils/permission";
import { saveYamlAsFile } from "@/views/domain/kubeHud/utils/file";
// import { downloadYaml } from "@/utils/actions";
// import { checkPermissions } from "@/utils/permission";
// import { deleteSecrets, getSecret, listSecrets } from "@/api/secrets";
const { secretRepo } = useK8SApi();
const types = [
  "Opaque",
  "kubernetes.io/dockerconfigjson",
  "kubernetes.io/basic-auth",
  "kubernetes.io/ssh-auth",
  "kubernetes.io/tls"
];

const { t } = useI18n();

type Prop = {};
const props = withDefaults(defineProps<Prop>(), {});
const { router } = useVerifyRouter();

const query = reactive({
  paginationConfig: {
    currentPage: 1,
    pageSize: 10,
    total: 0
  },
  searchConfig: {
    keywords: ""
  }
});
const secretList = ref<Secret[]>([]);
const selections = ref<Secret[]>([]);

const uiState = reactive({
  loading: false,
  buttons: [
    {
      label: t("commons.button.edit"),
      icon: "el-icon-edit",
      click: row => {
        onShouldViewEditDetails(row, { edit: true });
      },
      disabled: row => {
        return (
          !checkPermissions({
            scope: "namespace",
            apiGroup: "",
            resource: "secrets",
            verb: "update"
          }) || types.indexOf(row.type) === -1
        );
      }
    },
    {
      label: t("commons.button.edit_yaml"),
      icon: "el-icon-edit",
      click: row => {
        onShouldViewEditDetails(row, { edit: true, yamlShow: "true" });
      },
      disabled: async () => {
        return !(await checkPermissions({
          scope: "namespace",
          apiGroup: "",
          resource: "secrets",
          verb: "update"
        }));
      }
    },
    {
      label: t("commons.button.download_yaml"),
      icon: "el-icon-download",
      click: row => {
        // downloadYaml(
        //   row.metadata.name + ".yml",
        //   getSecret(this.cluster, row.metadata.namespace, row.metadata.name)
        // );
        secretRepo
          .getSecretDetail({
            namespace: row.metadata.namespace,
            name: row.metadata.name
          })
          .then(res => {
            if (res) {
              saveYamlAsFile(res, row.metadata.name + ".yaml");
            }
          });
      }
    },
    {
      label: t("commons.button.delete"),
      icon: "el-icon-delete",
      click: row => {
        onShouldDelete(row);
      },
      disabled: async () => {
        return !(await checkPermissions({
          scope: "namespace",
          apiGroup: "",
          resource: "secrets",
          verb: "delete"
        }));
      }
    }
  ]
});

const onShouldCreate = () => {
  router.push({
    name: KRouteSecret.Create.name,
    query: { yamlShow: "false" }
  });
};

const onShouldYamlCreate = () => {
  router.push({
    name: KRouteSecret.Create.name,
    query: { yamlShow: "false" }
  });
};

const onSHouldViewDetails = (row: Secret, params?: any) => {
  router.push({
    name: KRouteSecret.Details.name,
    params: {
      namespace: row.metadata.namespace,
      name: row.metadata.name,
      ...(params || {})
    }
  });
};

const onShouldViewEditDetails = (row: Secret, query?: any) => {
  router.push({
    name: KRouteSecret.Edit.name,
    query: {
      namespace: row.metadata.namespace,
      name: row.metadata.name,
      ...(query || {})
    }
  });
};

const reloadSecretList = async () => {
  uiState.loading = true;
  selections.value = [];
  const { items } = await secretRepo.getSecret({});
  secretList.value = items;
  uiState.loading = false;
};

const onShouldDelete = (row?: Secret) => {
  ElMessageBox.alert(
    t("commons.confirm.delete", [row?.metadata.name]),
    t("commons.button.delete"),
    {
      confirmButtonText: t("commons.button.confirm"),
      cancelButtonText: t("commons.button.cancel"),
      type: "warning"
    }
  ).then(() => {
    if (
      row &&
      selections.value.findIndex(r => row.metadata.name === r.metadata.name) ===
        -1
    ) {
      selections.value.push(row);
    }

    Promise.all(
      selections.value.map(s =>
        secretRepo.deleteSecret({ namespace: s.metadata.namespace, data: s })
      )
    ).then(() => {
      reloadSecretList();
    });
  });
};

onMounted(() => {
  reloadSecretList();
});
</script>

<style scoped></style>
